package libs

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"time"
)

var (
	db  *gorm.DB
	err error
)

type Model struct {
	ID        uint       `gorm:"primary_key" json:"id"`
	CreatedAt time.Time  `json:"created_at,omitempty"`
	UpdatedAt time.Time  `json:"updated_at,omitempty"`
	DeletedAt *time.Time `sql:"index" json:"deleted_at,omitempty"`
}

type ATime time.Time

func init() {
	dsn := fmt.Sprintf(
		"%s:%s@tcp(%s)/%s?charset=%s&parseTime=True&loc=Local",
		config.DB.User,
		config.DB.Pass,
		config.DB.Host,
		config.DB.DbName,
		config.DB.Charset,
	)
	db, err = gorm.Open(mysql.Open(dsn),
		&gorm.Config{
			NamingStrategy: schema.NamingStrategy{
				SingularTable: true,
			},
		},
	)
	if err != nil {
		panic(err)
	}

	// 禁止表名负数
	sqlDB, _ := db.DB()

	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(time.Hour)
	//db.SingularTable(true)
	//db.LogMode(false)
	//db.DB().SetMaxOpenConns(10)
	//db.DB().SetMaxIdleConns(5)

	// 自动时间戳
	//db.Callback().Create().Register("gorm:update_time_stamp", func(scope *gorm.Scope) {
	//	if !scope.HasError() {
	//		var val = scope.Value
	//
	//		if createTimeField, ok := scope.FieldByName("CreateTime"); ok {
	//			if createTimeField.IsBlank {
	//				createTimeField.Set()
	//			}
	//		}
	//	}
	//})

	//db.Callback().Query().After("gorm:query").Register("ke:AfterFind", func(scope *gorm.Scope) {
	//	arr, ok := scope.Get("gorm:array")
	//	if ok {
	//		fmt.Printf("%v", arr)
	//	}
	//	println("wewe")
	//
	//})
}

func GetDb() *gorm.DB {
	return db
}
